package com.example.administrator.baikangxing.utils;

import android.content.Context;

import com.example.administrator.baikangxing.Dao.OperateData;
import com.example.administrator.baikangxing.MyApplication;
import com.example.administrator.baikangxing.config.Constants;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.loopj.android.http.TextHttpResponseHandler;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import cz.msebera.android.httpclient.Header;

public class HttpUtil {
    private static final int SOCKET_TIMEOUT = 2000; //默认超时时间
    private static HttpUtil instance = new HttpUtil();
    private AsyncHttpClient httpClient;

    private HttpUtil() {
        httpClient = new AsyncHttpClient();
        httpClient.setTimeout(SOCKET_TIMEOUT);
    }

    public static HttpUtil getInstance() {
        return instance;
    }


    /**
     * 从网络返回String数据
     *
     * @param context  上下文
     * @param url      请求地址
     * @param callBack 回调
     */
    public void getStringFromNet(Context context, String url, final CallBackDependString callBack) {
        httpClient.get(context, url, new TextHttpResponseHandler() {
            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                if (callBack != null) {
                    callBack.onSuccess(responseString);
                }
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, String responseString) {
                if (callBack != null) {
                    callBack.onFail(responseString);
                }
            }
        });
    }


    public static JSONArray getJsonArray(String url) {
        try {
            URL neturl = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) neturl.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(5000);
            conn.setRequestProperty("Charset", "UTF-8");
            if (conn.getResponseCode() == 200) {
                InputStream is = conn.getInputStream();
                StringBuffer out = new StringBuffer();
                byte[] b = new byte[4096];
                for (int n; (n = is.read(b)) != -1; ) {
                    out.append(new String(b, 0, n));
                }
                return new JSONArray(out.toString());
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 这个是从网络返回byte数据
     *
     * @param context  上下文
     * @param url      请求地址
     * @param callBack 回调
     */
    public void getByteFromNet(Context context, String url, final CallBackDependByte callBack) {
        httpClient.get(context, url, new AsyncHttpResponseHandler() {

            @Override
            public void onStart() {
                super.onStart();
                if (callBack != null) {
                    callBack.onStart();
                }
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                if (callBack != null) {
                    callBack.onSuccess(responseBody);
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                if (callBack != null) {
                    callBack.onFail(responseBody);
                }
            }

            @Override
            public void onProgress(long bytesWritten, long totalSize) {
                super.onProgress(bytesWritten, totalSize);
                if (callBack != null) {
                    callBack.onProgress(bytesWritten, totalSize);
                }
                
                
            }
        });
    }

    /**
     * 请求网络返回的是json数据
     *
     * @param context  上下文
     * @param url      请求地址
     * @param callBack 回调
     */
    public void getJsonFromNet(Context context, String url, final CallBackDependJson callBack) {
        httpClient.get(context, url, new JsonHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONArray response) {
                super.onSuccess(statusCode, headers, response);
                if (callBack != null) {
                    LogUtil.e("网络请求的返回码", statusCode + "");
                    callBack.onSuccess(statusCode, response);
                }
            }


            @Override
            public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONArray errorResponse) {
                super.onFailure(statusCode, headers, throwable, errorResponse);
                LogUtil.e("网络请求失败的状态码");
                if (callBack != null) {
                    callBack.onFail(statusCode, errorResponse);
                }
            }

            @Override
            public void onFinish() {
                super.onFinish();
                if (callBack != null) {
                    callBack.onFinish();
                }
                
            }
        });
    }

    /**
     * 將一個文件上传到服务器
     *
     * @param url  上传地址
     * @param path 文件路径
     * @param key  key值
     * @throws Exception s
     */
    public void postFilesToNet(String url, String path, String key, final CallBackPostFile callBack) throws Exception {
        File file = new File(path);
        if (file.exists() && file.length() > 0) {
            LogUtil.e("上传的文件存在");
            try {
                RequestParams params = new RequestParams();
                params.put(key, file);
                httpClient.post(url, params, new JsonHttpResponseHandler() {
                    @Override
                    public void onSuccess(int statusCode, Header[] headers, JSONArray response) {
                        super.onSuccess(statusCode, headers, response);
                        if (callBack != null) {
                            callBack.onSuccess(statusCode, response);
                        }
                    }

                    @Override
                    public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONArray errorResponse) {
                        super.onFailure(statusCode, headers, throwable, errorResponse);
                        if (callBack != null) {
                            callBack.onFail(statusCode, errorResponse);
                        }
                    }

                    @Override
                    public void onProgress(long bytesWritten, long totalSize) {
                        super.onProgress(bytesWritten, totalSize);
                        if (callBack != null) {
                            callBack.onProgress(bytesWritten, totalSize);
                        }
                    }
                });
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            ToastUtil.showToast("文件不存在");
        }
    }

    /**
     * 將一個文件上传到服务器
     *
     * @param url       上传地址
     * @param fileArray 文件路径
     * @param key       key值
     * @throws Exception s
     */
    public void postFileArrayToNet(String url, File[] fileArray, String key, final CallBackPostFile callBack) throws Exception {
        try {
            RequestParams params = new RequestParams();
            params.put(key, fileArray);
            httpClient.post(url, params, new JsonHttpResponseHandler() {
                @Override
                public void onSuccess(int statusCode, Header[] headers, JSONArray response) {
                    super.onSuccess(statusCode, headers, response);
                    if (callBack != null) {
                        callBack.onSuccess(statusCode, response);
                    }
                }

                @Override
                public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONArray errorResponse) {
                    super.onFailure(statusCode, headers, throwable, errorResponse);
                    if (callBack != null) {
                        callBack.onFail(statusCode, errorResponse);
                    }
                }

                @Override
                public void onProgress(long bytesWritten, long totalSize) {
                    super.onProgress(bytesWritten, totalSize);
                    if (callBack != null) {
                        callBack.onProgress(bytesWritten, totalSize);
                    }
                }

                @Override
                public void onFinish() {
                    super.onFinish();
                    if (callBack != null) {
                        callBack.onFinish();
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 將一個文件上传到服务器
     *
     * @param url  上传地址
     * @param path 文件路径
     * @param key  key值
     * @throws Exception
     */
    public void postFileToNet(String url, String path, String key, final CallBackPostFiles callBack) throws Exception {
        File file = new File(path);
        if (file.exists() && file.length() > 0) {
            try {
                RequestParams params = new RequestParams();
                params.put(key, file);
                httpClient.post(url, params, new AsyncHttpResponseHandler() {
                    @Override
                    public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                        if (callBack != null) {
                            callBack.onSuccess(responseBody);
                        }
                    }

                    @Override
                    public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                        if (callBack != null) {
                            callBack.onFail(responseBody);
                        }
                    }

                    @Override
                    public void onProgress(long bytesWritten, long totalSize) {
                        super.onProgress(bytesWritten, totalSize);
                        if (callBack != null) {
                            callBack.onProgress(bytesWritten, totalSize);
                        }
                    }
                });
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            ToastUtil.showToast("文件不存在");
        }
    }

    /**
     * 登录post请求的接口
     *
     * @param url      上传地址
     * @param str      上传内容
     * @param key      key值
     * @param callBack 回调
     */
    public void postLoginString(String url, String[] key, String[] str, final CallBackPostString callBack) {
        RequestParams params = new RequestParams();
        for (int i = 0; i < str.length; i++) {
            params.put(key[i],str[i]);
        }
        httpClient.post(url, params, new JsonHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                super.onSuccess(statusCode, headers, response);
                if (callBack != null) {
                    callBack.onSuccess(response);
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
                super.onFailure(statusCode, headers, throwable, errorResponse);
                if (callBack != null) {
                    callBack.onFail(errorResponse);
                }
            }

            @Override
            public void onProgress(long bytesWritten, long totalSize) {
                super.onProgress(bytesWritten, totalSize);
                if (callBack != null) {
                    callBack.onProgress(bytesWritten, totalSize);
                }
            }
        });
    }
    /**
     * 普通post请求的接口
     *
     * @param url      上传地址
     * @param str      上传内容
     * @param key      key值
     * @param callBack 回调
     */
    public void postString(String url, String[] key, String[] str, final CallBackPostString callBack) {
        RequestParams params = new RequestParams();
        for (int i = 0; i < str.length; i++) {
            params.put(key[i],str[i]);
        }
        params.put("token", OperateData.getStringData(MyApplication.context, Constants.APP_TOKEN));
        LogUtil.e("token:"+OperateData.getStringData(MyApplication.context, Constants.APP_TOKEN));
        httpClient.post(url, params, new JsonHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                super.onSuccess(statusCode, headers, response);
                try {
                    if (callBack != null ){
                        if( response.getString("errorCode").equals("101")){
                            ToastUtil.showToast("登录失效，请重新登录");
                        }else {
                            callBack.onSuccess(response);
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
                super.onFailure(statusCode, headers, throwable, errorResponse);
                if (callBack != null) {
                    callBack.onFail(errorResponse);
                }
            }

            @Override
            public void onProgress(long bytesWritten, long totalSize) {
                super.onProgress(bytesWritten, totalSize);
                if (callBack != null) {
                    callBack.onProgress(bytesWritten, totalSize);
                }
            }
        });
    }


    /**
     * 返回值是String的回调接口
     */
    public interface CallBackDependString {

        void onSuccess(String successString);

        void onFail(String failString);

    }

    /**
     * 返回值是Byte的回调接口
     */
    public interface CallBackDependByte {

        void onSuccess(byte[] successByte);

        void onFail(byte[] failByte);

        void onProgress(long bytesWritten, long totalSize);

        void onStart();
    }

    /**
     * 返回值是Json的回调接口
     */
    public interface CallBackDependJson {
        void onSuccess(int statusCode, JSONArray successJson);

        void onFail(int statusCode, JSONArray failJson);

        void onFinish();
    }

    /**
     * 上传文件的的回调接口
     */
    public interface CallBackPostFiles {
        void onSuccess(byte[] responseBody);

        void onFail(byte[] responseBody);

        void onProgress(long bytesWritten, long totalSize);
    }

    /**
     * 上传文件的的回调接口
     */
    public interface CallBackPostFile {
        void onSuccess(int statusCode, JSONArray successFiles);

        void onFail(int statusCode, JSONArray failFiles);

        void onProgress(long bytesWritten, long totalSize);

        void onFinish();
    }

    /**
     * 上传字符串的的回调接口
     */
    public interface CallBackPostString {
        void onSuccess(JSONObject successString);

        void onFail(JSONObject failString);

        void onProgress(long bytesWritten, long totalSize);
    }
}
